package cn.matezk.lianlian.controller;

import cn.matezk.lianlian.framework.PaymentConfiguration;
import cn.matezk.lianlian.service.IPaymentService;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.model.Transaction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("payment")
@Slf4j
public class PaymentController extends BaseController {
    @Autowired
    private PaymentConfiguration paymentConfig;
    @Autowired
    private IPaymentService paymentService;

    @PostMapping("notify/{merchantId}")
    public void notify(@RequestHeader Map<String, String> headers, @PathVariable String merchantId, @RequestBody(required = false) String requestBody) throws InterruptedException {
        RequestParam requestParam = new RequestParam.Builder()
                .serialNumber(headers.get("wechatpay-serial"))
                .nonce(headers.get("wechatpay-nonce"))
                .signature(headers.get("wechatpay-signature"))
                .timestamp(headers.get("wechatpay-timestamp"))
                .signType(headers.get("wechatpay-signature-type"))
                .body(requestBody)
                .build();
        NotificationConfig certificateConfig = paymentConfig.buildNotificationConfig(merchantId);
        NotificationParser parser = new NotificationParser(certificateConfig);
        // 以支付通知回调为例，验签、解密并转换成 Transaction
        Transaction transaction = parser.parse(requestParam, Transaction.class);
        paymentService.doNotify(transaction);
    }
}
